import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import cloneDeep from 'lodash/cloneDeep';
import {Button, Form, Row, Col, Card, Spin, Modal, message as msg} from 'antd';
import {getDealersQuickly, getDealers} from './api';
import {FORM_OPTIONS} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import {newOrUpdateOrderValidator} from './validator';
import {injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import WrappedInputNumber from '../common/WrappedInputNumber';
import WrappedDatePicker from '../common/WrappedDatePicker';
import TextInput from 'Shared/components/TextInput';
import {salesOPSubmitLimitType, baseDataStatus} from '../Enum';
const typeList = salesOPSubmitLimitType.toList(language);
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {
            status: baseDataStatus.生效
        }
    };

    componentDidMount() {
        this.ismounted = true;
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }

    handleFilterChange = (value, name) => {
        if(name === 'submitEndDay' && value === 31)
            msg.warn(this.props.intl.formatMessage({
                id: 'message.submitEndDay',
                defaultMessage: '这是月底最后一天'
            }));
        if(name === 'submitNoticeEndDay' && value === 31)
            msg.warn(this.props.intl.formatMessage({
                id: 'message.submitEndDay',
                defaultMessage: '这是月底最后一天'
            }));
        if(name === 'expirationDate' && value === null)
            msg.warn(this.props.intl.formatMessage({
                id: 'message.expirationDate',
                defaultMessage: '此设置永远有效'
            }));
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    
    onClickReturnBtn = () => {
        this.props.onCancel();
    }

    onSubmit = () => {
        if(!this.state.data.brandId && this.props.initEnum.brands.length === 1)
            // eslint-disable-next-line react/no-direct-mutation-state
            this.state.data.brandId = this.props.initEnum.brands[0].value;
        const isValid = newOrUpdateOrderValidator(this.state.data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    
    onSelectDealer = (condition = {}) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    ...newData,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                }
            };
        });
    };
    onChangeBrand = (value, name) => {
        if(this.state.data.brandId !== undefined && this.state.data.brandId !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch',
                    defaultMessage: '变更品牌，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onBrandSwitch(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value
                }),
                hasOperat: true
            });
    }
    onBrandSwitch = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value,
            dealerId: undefined,
            type: undefined,
            submitBeginDay: undefined,
            submitEndDay: undefined,
            submitNoticeBeginDay: undefined,
            submitNoticeEndDay: undefined,
            effectiveDate: undefined,
            expirationDate: undefined,
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onChangeDealer = (value, name) => {
        if(!this.state.data.brandId)
            return msg.warn(this.props.intl.formatMessage({
                id: 'newPanel.message.brand',
                defaultMessage: '请选择品牌'
            }));
        if(this.state.data.dealerId !== undefined && this.state.data.dealerId !== value)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch2',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch3',
                    defaultMessage: '变更总代，将会清空清单数据，是否清空？'
                }),
                onOk: () => this.onDealerSwitch(value, name)
            });
        else
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value
                }),
                hasOperat: true
            });
    }
    onDealerSwitch = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value,
            dealerId: undefined,
            type: undefined,
            submitBeginDay: undefined,
            submitEndDay: undefined,
            submitNoticeBeginDay: undefined,
            submitNoticeEndDay: undefined,
            effectiveDate: undefined,
            expirationDate: undefined,
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    render() {
        const data = this.state.data;
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const queryCondition = {
            brandId: (this.props.initEnum.brands.length === 1 ? this.props.initEnum.brands[0].value : data.brandId)
        };
        const validateBrand = !data.brandId && this.state.validate ? 'error' : null;
        const validateType = !data.type && this.state.validate ? 'error' : null;
        const validateSubmitBeginDay = !data.submitBeginDay && this.state.validate ? 'error' : null;
        const validateSubmitEndDay = !data.submitEndDay && this.state.validate ? 'error' : null;
        const validateEffectiveDate = !data.effectiveDate && this.state.validate ? 'error' : null;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;
        const submitable = hasPermissions(PERMISSION.add, pagePermission);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'newPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.brand',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBrand} required>
                                        {this.props.initEnum.brands.length === 1 ? this.props.initEnum.brands[0].text : <WrappedSelect
                                            allowClear
                                            name="brandId"
                                            value={data.brandId}
                                            options={this.props.initEnum.brands}
                                            onChange={this.onChangeBrand}/>
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item} required>
                                        {data.brandId || this.props.initEnum.brands.length === 1 ? (<DealerSelectPanel
                                            getDealerSimple={getDealersQuickly}
                                            getDealers={getDealers}
                                            value={dealerInfo}
                                            conditions={queryCondition}
                                            onChange={this.onChangeDealer}
                                            onSelect={this.onSelectDealer} />) : (<TextInput name="dealerId"
                                            value={''} disabled={true} placeholder={this.props.intl.formatMessage({
                                                id: 'newPanel.dealerComp.placeholder',
                                                defaultMessage: '请先选择品牌'
                                            })} />) }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.form.type',
                                        defaultMessage: '提报时效类型'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateType} required>
                                        <WrappedSelect
                                            allowClear
                                            name="type"
                                            value={data.type}
                                            options={typeList}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.submitBeginDay',
                                        defaultMessage: '每月提报开始日'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateSubmitBeginDay} required>
                                        <WrappedInputNumber
                                            min={1}
                                            max={31}
                                            name="submitBeginDay"
                                            value={data.submitBeginDay}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.submitEndDay',
                                        defaultMessage: '每月提报结束日'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateSubmitEndDay} required>
                                        <WrappedInputNumber
                                            min={1}
                                            max={31}
                                            name="submitEndDay"
                                            value={data.submitEndDay}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.submitNoticeBeginDay',
                                        defaultMessage: '提报提醒开始日'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedInputNumber
                                            min={1}
                                            max={31}
                                            name="submitNoticeBeginDay"
                                            value={data.submitNoticeBeginDay}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.submitNoticeEndDay',
                                        defaultMessage: '提报提醒结束日'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedInputNumber
                                            min={1}
                                            max={31}
                                            name="submitNoticeEndDay"
                                            value={data.submitNoticeEndDay}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.effectiveDate',
                                        defaultMessage: '生效日期'
                                    })} {...FORM_OPTIONS.item} validateStatus={validateEffectiveDate} required>
                                        <WrappedDatePicker
                                            name="effectiveDate"
                                            value={data.effectiveDate}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.expirationDate',
                                        defaultMessage: '失效日期'
                                    })} {...FORM_OPTIONS.item}>
                                        <WrappedDatePicker
                                            name="expirationDate"
                                            value={data.expirationDate}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'newPanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    initEnum: getinitEnumData(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: data => dispatch(onSubmit(data)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url()),
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
